<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="3.5">
        <div class="sp-commodity">订单列表</div>
      </el-col>
      <el-col :span="3">
        <div>
          <el-cascader :options="platFormOptions" :show-all-levels="false" @change="handleNodeClick"
            style="margin-top: 8px"></el-cascader>
        </div>
      </el-col>
    </el-row>
    <div class="DOe5g">
      <div class="qjd7T">
        <div class="tab-order">
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane :label="`Unshipped(${UnshippedTotal})`" name="unshipped">
            </el-tab-pane>
            <el-tab-pane :label="`Shipped(${ShippedTotal})`" name="shipped">
            </el-tab-pane>
            <el-tab-pane :label="`Canceled(${CanceledTotal})`" name="canceled">
            </el-tab-pane>
            <el-tab-pane :label="`AII(${AIITotal})`" name="aii"> </el-tab-pane>
            <div class="input-container">
              <el-input placeholder="Search" v-model="input" class="input-with-selects"
                @keyup.enter.native="orderQuery">
                <el-select v-model="select" slot="prepend" placeholder="请选择" class="select-input">
                  <el-option label="Order #" value="1"></el-option>
                  <el-option label="PO #" value="2"></el-option>
                  <el-option label="SKU" value="3"></el-option>
                  <el-option label="GTIN" value="4"></el-option>
                  <el-option label="Customer First Name" value="5"></el-option>
                  <el-option label="Customer Last Name" value="6"></el-option>
                </el-select>
                <el-button slot="append" icon="el-icon-search" @click="orderQuery" v-hasPermi="['walmart:order:list']"></el-button>
              </el-input>
              <div class="div-filters" @click="drawer = true">
                <i class="el-icon-s-operation"></i>
                <span>Filters({{ selectedFiltersCount }})</span>
              </div>
            </div>
            <div class="div-items">
              <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange"
                style="width: 100%" height="600px">
                <el-table-column type="selection" align="center" fixed />
                <el-table-column label="Item" width="100" fixed>
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <image-preview :src="item.imageUrl" :width="50" :height="50" />
                      <br />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="Purchase order#" align="center" prop="purchaseOrderId" width="150" fixed />
                <el-table-column label="Order#" align="center" prop="customerOrderId" width="150" fixed />
                <el-table-column label="Order date" align="center" prop="orderDate" width="150" sortable>
                  <template slot-scope="scope">
                    {{ scope.row.orderDate   ? scope.row.orderDate.split('T')[0]   : '' }}
                  </template>
                </el-table-column>
                <el-table-column label="Ship by" align="center" prop="estimatedShipDate" width="150" sortable>
                  <template slot-scope="scope">
                    {{ scope.row.estimatedShipDate   ? scope.row.estimatedShipDate.split('T')[0]   : '' }}
                  </template>
                </el-table-column>
                <el-table-column label="Order total" align="center" prop="totalAmount" width="150">
                  <template slot-scope="scope">
                    <span>${{ scope.row.totalAmount }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="Customer" align="center" prop="name" width="200" />
                <el-table-column label="Fulfilled by" align="center" prop="fulfillmentOption" width="150">
                  <template slot-scope="scope">
                    <span v-if="scope.row.fulfillmentOption === 'DELIVERY'">Walmart</span>
                    <span v-else>{{ scope.row.fulfillmentOption }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="Ship method" align="center" width="150">
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <span>{{ item.shipMethod }}</span><br />
                    </span> </template></el-table-column>

                <el-table-column label="链接名称" width="400">
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <el-popover placement="top-start" title="链接名称" width="600" trigger="hover"
                        :content="item.productName">
                        <span slot="reference">{{ item.productName.slice(0, 39)
                        }}<span v-if="item.productName.length > 39">...</span></span>
                      </el-popover>
                      <br />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="SKU" width="130">
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <span>{{ item.sku }}</span><br />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="GTIN" width="130">
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <span>{{ item.gtin }}</span><br />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="Qty" align="center" width="50">
                  <template slot-scope="scope">
                    <span v-for="item in scope.row.orderItemList" :key="item.id">
                      <span>{{ item.qty }}</span><br />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="Status" align="center" width="150" fixed="right">
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.orderItemList" :key="item.id">
                      <div>
                        <dict-tag :options="dict.type.walmart_order_status" :value="item.status" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top: -11px; height: 50px">
              <pagination v-show="total > 0" :total="total" :page.sync="queryParam.pageNum"
                :limit.sync="queryParam.pageSize" @pagination="getOrderList()" />
            </div>
          </el-tabs>
        </div>
      </div>
    </div>
    <el-drawer title="Filters" :visible.sync="drawer" :direction="direction" :size="450">
      <div class="filters-line"></div>
      <div class="collapse-div">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <div>
                Status
                <br />
                <div v-if="!activeNames || activeNames.length === 0">
                  <el-tag :key="statusTag" v-for="statusTag in statusList" closable :disable-transitions="false"
                    @close="handleStatus(statusTag)">
                    {{ statusTag }}
                  </el-tag>
                </div>
              </div>
            </template>
            <el-checkbox-group v-model="statusList" class="checkbox-group">
              <el-checkbox v-for="option in filteredOptions" :key="option" :label="option"></el-checkbox>
            </el-checkbox-group>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div>
                Order date
                <br />
                <div v-if="!activeNames || activeNames.length === 0">
                  <el-tag :key="orderDate" v-for="orderDate in orderDateList" closable :disable-transitions="false"
                    @close="handleOrderDates(orderDate)">
                    {{ orderDate }}
                  </el-tag>
                </div>
              </div>
            </template>
            <el-radio-group v-model="orderDateList" @change="processOrderDate">
              <el-radio label="Today">Today</el-radio><br />
              <el-radio label="Sinceyesterday">Since yesterDay</el-radio><br />
              <el-radio label="Last 3 days">Last 3 days</el-radio><br />
              <el-radio label="Last 7 days">Last 7 days</el-radio><br />
              <el-radio label="Last 14 days">Last 14 days</el-radio><br />
              <el-radio label="Last 30 days">Last 30 days</el-radio><br />
              <el-radio label="Last 90 days">Last 90 days</el-radio><br />
              <el-radio label="Last 180 days">Last 180 days</el-radio><br />
            </el-radio-group>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 按钮部分 -->
      <div class="footer-buttons">
        <el-button type="default" @click="clearAll">Clear all</el-button>
        <el-button type="primary" @click="applyFilters">Apply</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getOrderList, getOrderSummary } from "@/api/walmart/items";
import { getPlatFormTree } from "@/api/walmart/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  dicts: ["walmart_order_status"],
  data() {
    return {
      platFormOptions: [],
      activeName: "aii",
      input: "",
      select: "1",
      // 遮罩层
      loading: false,
      // 非多个禁用
      multiple: true,
      orderList: [],
      orderId: [],
      // 总条数
      total: 0,
      queryParam: {
        pageNum: 1,
        pageSize: 50,
        authId: null,
        purchaseOrderId: null,
        customerOrderId: null,
        sku: null,
        firstName: null,
        lastName: null,
      },
      visible: false,

      AIITotal: 0,
      CanceledTotal: 0,
      ShippedTotal: 0,
      UnshippedTotal: 0,
      statusList: [],
      orderDateList: "",
      drawer: false,
      direction: "rtl",
      activeNames: [],
      startDate: null, // 处理后的开始日期
      endDate: null, // 处理后的结束日期
      orderSummaryParam: {},
      allOptions: {
        unshipped: ["New", "Acknowledged"],
        shipped: ["Shipped", "Delivered"],
        canceled: ["Cancelled"],
        aii: ["New", "Shipped", "Cancelled", "Acknowledged", "Delivered"],
      },
    };
  },
  computed: {
    // 计算已选的过滤器数量
    selectedFiltersCount() {
      let count = 0;
      if (this.statusList.length > 0) count++; // Status 被选中
      if (this.orderDateList) count++; // Order date 被选中
      return count;
    },
    filteredOptions() {
      // 根据 activeTab 动态过滤选项
      return this.allOptions[this.activeName] || [];
    },
  },
  created() {
    this.getPlatForm();
    this.getOrderSummary();
  },
  methods: {
    /** 查询店铺名称列表 */
    getPlatForm() {
      getPlatFormTree().then((response) => {
        this.platFormOptions = response.data;
      });
    },
    handleNodeClick(data) {
      this.queryParam.authId = data[2];
      this.orderSummaryParam.authId = data[2];
      this.getOrderList();
      this.getOrderSummary();
    },
    getOrderList() {
      this.loading = true;
      getOrderList(this.queryParam).then((response) => {
        this.loading = false;
        this.orderList = response.rows;
        this.total = response.total;
      });
    },
    handleSelectionChange(selection) {
      this.orderId = selection.map((item) => item.orderId);
      this.multiple = !selection.length;
    },
    orderQuery() {
      this.queryParam.customerOrderId = "";
      this.queryParam.purchaseOrderId = "";
      this.queryParam.sku = "";
      this.queryParam.gtin = "";
      this.queryParam.firstName = "";
      this.queryParam.lastName = "";

      const trimmedInput = this.input.trim();

      if (this.select == "1") {
        this.queryParam.customerOrderId = trimmedInput;
        this.getOrderList();
      } else if (this.select == "2") {
        this.queryParam.purchaseOrderId = trimmedInput;
        this.getOrderList();
      } else if (this.select == "3") {
        this.queryParam.sku = trimmedInput;
        this.getOrderList();
      } else if (this.select == "4") {
        this.queryParam.gtin = trimmedInput;
        this.getOrderList();
      } else if (this.select == "5") {
        this.queryParam.firstName = trimmedInput;
        this.getOrderList();
      } else if (this.select == "6") {
        this.queryParam.lastName = trimmedInput;
        this.getOrderList();
      }
    },
    handleTabClick(tab) {
      this.queryData(tab.name);
    },
    /** 汇总订单状态*/
    getOrderSummary() {
      if (!this.orderSummaryParam.authId) {
        return;
      }
      this.orderSummaryParam.startDate = this.startDate;
      this.orderSummaryParam.endDate = this.endDate;
      this.orderSummaryParam.statusList = this.statusList;
      getOrderSummary(this.orderSummaryParam).then((response) => {
        this.UnshippedTotal = response.unshipped;
        this.ShippedTotal = response.shipped;
        this.CanceledTotal = response.canceled;
        this.AIITotal = response.allOrders;
      });
    },
    queryData(tabName) {
      // 根据 tabName 执行查询，下面是一个简单的示例
      switch (tabName) {
        case "unshipped":
          this.queryParam.statusList = ["New", "Acknowledged"];
          this.input = "";
          this.getOrderList();
          break;
        case "shipped":
          this.queryParam.statusList = ["Shipped", "Delivered"];
          this.input = "";
          this.getOrderList();
          break;
        case "canceled":
          this.queryParam.statusList = ["Cancelled"];
          this.input = "";
          this.getOrderList();
          break;
        case "aii":
          this.queryParam.statusList = [];
          this.input = "";
          this.getOrderList();
          break;
        default:
          console.log("无效的 Tab");
      }
    },
    handleStatus(statusTag) {
      this.statusList.splice(this.statusList.indexOf(statusTag), 1);
    },
    handleOrderDates(orderDate) {
      this.orderDateList.splice(this.orderDateList.indexOf(orderDate), 1);
      this.orderDateList = "";
      this.startDate = null;
      this.endDate = null;
    },
    // 清除所有选项
    clearAll() {
      this.statusList = [];
      this.orderDateList = "";
      this.startDate = "";
      this.endDate = "";
    },
    // 应用筛选条件
    applyFilters() {
      this.queryParam.startDate = this.startDate;
      this.queryParam.endDate = this.endDate;
      this.queryParam.statusList = this.statusList;
      this.drawer = false; // 关闭抽屉
      this.getOrderList();
      this.getOrderSummary();
    },
    // 处理 orderDateList，转换为具体的日期范围
    processOrderDate() {
      //const today = new Date();
      const pacificTimezone = "America/Los_Angeles";
      const today = new Date(
        new Date().toLocaleString("en-US", { timeZone: pacificTimezone })
      );
      const formattedDateTime = this.getFormattedDateTime(today); // 获取美西时区的日期时分秒
      const formattedDate = this.getFormattedDate(today); // 获取美西时区的日期

      switch (this.orderDateList) {
        case "Today":
          this.startDate = formattedDateTime; // 当天开始
          this.endDate = formattedDate + " 23:59:59"; // 当天结束
          break;

        case "Sinceyesterday":
          const yesterday = new Date(today);
          yesterday.setDate(today.getDate() - 1);
          this.startDate = this.getFormattedDateTime(yesterday); // 昨天开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 3 days":
          const threeDaysAgo = new Date(today);
          threeDaysAgo.setDate(today.getDate() - 3);
          this.startDate = this.getFormattedDateTime(threeDaysAgo) ; // 3 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 7 days":
          const sevenDaysAgo = new Date(today);
          sevenDaysAgo.setDate(today.getDate() - 7);
          this.startDate = this.getFormattedDateTime(sevenDaysAgo); // 7 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 14 days":
          const fourteenDaysAgo = new Date(today);
          fourteenDaysAgo.setDate(today.getDate() - 14);
          this.startDate = this.getFormattedDateTime(fourteenDaysAgo); // 14 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 30 days":
          const thirtyDaysAgo = new Date(today);
          thirtyDaysAgo.setDate(today.getDate() - 30); // 30 天前
          this.startDate = this.getFormattedDateTime(thirtyDaysAgo); // 30 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 90 days":
          const ninetyDaysAgo = new Date(today);
          ninetyDaysAgo.setDate(today.getDate() - 90); // 90 天前
          this.startDate = this.getFormattedDateTime(ninetyDaysAgo); // 90 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        case "Last 180 days":
          const oneHundredEightyDaysAgo = new Date(today);
          oneHundredEightyDaysAgo.setDate(today.getDate() - 180); // 180 天前
          this.startDate =
            this.getFormattedDateTime(oneHundredEightyDaysAgo); // 180 天前开始
          this.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;

        default:
          this.startDate = null;
          this.endDate = null;
      }
    },
    getFormattedDateTime(date) {
      // 从已传入的美西时间提取日期部分
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getFormattedDate(date) {
      // 从已传入的美西时间提取日期部分
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
};
</script>

<style>
input[aria-hidden=true] {
  display: none !important;
}

.sp-commodity {
  font-size: 36px;
  font-weight: bold;
  margin-top: 5px;
}

.DOe5g {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-align: start;
  -ms-flex-align: start;
  align-items: flex-start;
  position: static;
  background: #fff;
  -webkit-box-shadow: 0 0 2.5px 2.5px rgb(0 0 0 / 8%);
  box-shadow: 0 0 2.5px 2.5px rgb(0 0 0 / 8%);
  -webkit-box-flex: 0;
  -ms-flex: none;
  flex: none;
  -webkit-box-ordinal-group: 1;
  -ms-flex-order: 0;
  order: 0;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  -webkit-box-flex: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
  margin: 0;
  border-radius: 8px;
}

.qjd7T {
  width: 100%;
  min-height: 35vh;
}

.input-container {
  display: flex;
  align-items: center;
  margin-left: 6px;
}

.input-with-selects {
  width: 1480px;
}

.input-with-selects .el-input-group__prepend {
  background-color: #fff;
}

.select-input {
  width: 160px;
}

.tab-order {
  width: 1600px;
  margin: 0 auto;
  /* 居中 */
}

.div-items {
  margin-top: 20px;
}

.top-centered {
  display: flex;
  align-items: flex-start;
}

.div-filters {
  width: 100px;
  height: 36px;
  border: 1px solid #e3e1e1;
  border-radius: 5px;
  margin-left: 10px;
  /* 调整距离，根据需要进行修改 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.div-filters i {
  margin-right: 5px;
  /* 调整距离，根据需要进行修改 */
}

.div-filters span {
  font-size: 14px;
  /* 设置字体大小，根据需要进行修改 */
}

.div-items {
  margin-top: 20px;
}

/*
.filters-line {
  border-top: 1px solid #e6ebf5;
  position: relative;
  top: 1px;
}
*/
.collapse-div {
  margin-left: 20px;
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.collapse-div .el-collapse-item__header {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: auto;
  line-height: 48px;
  background-color: #ffffff;
  color: #000000;
  cursor: pointer;
  border-bottom: 1px solid #e6ebf5;
  font-size: 15px;
  font-weight: 500;
  -webkit-transition: border-bottom-color 0.3s;
  transition: border-bottom-color 0.3s;
  outline: none;
}

.el-radio {
  margin-bottom: 10px;
  /* 设置下方间距为 20px，可以根据需要调整 */
  margin-top: 10px;
  /* 设置上方间距为 20px，可以根据需要调整 */
}

/* 设置底部按钮区域 */
.footer-buttons {
  position: absolute;
  /* 相对于 el-drawer 容器固定 */
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  /* 居中对齐按钮 */
  gap: 10px;
  /* 按钮之间的间距 */
  padding: 10px 15px;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
}

.footer-buttons .el-button {
  border-radius: 20px;
  /* 圆角按钮 */
  padding: 10px 20px;
  /* 调整按钮内边距 */
  font-size: 14px;
  /* 调整字体大小 */
  width: 40%;
}

.footer-buttons .el-button--primary {
  background-color: #007bff;
  /* 蓝色主按钮背景色 */
  color: #fff;
  /* 主按钮文字颜色 */
  border: none;
  /* 去除边框 */
}

.footer-buttons .el-button--default {
  border: 1px solid #ccc;
  /* 次按钮的边框颜色 */
  color: #000;
  /* 次按钮文字颜色 */
  background-color: #fff;
  /* 次按钮背景色 */
}

.checkbox-group .el-checkbox {
  display: block;
  /* 强制每个复选框换行 */
  padding-top: 10px;
}
</style>
